<template>
  <div v-if="show && editableSubmission" class="modal-overlay grading-modal-overlay" @click.self="closeModal">
    <div class="modal-content grading-modal-content">
      <div class="modal-header grading-modal-header">
        <h3>批改答卷 - {{ editableSubmission.userId }} <span class="exam-name-header">({{ currentExamNameFromStore }})</span></h3>
        <div class="grading-navigation">
          <button
            @click="handleNavigate('previous')"
            :disabled="submissionIndex === 0"
            class="btn btn-sm btn-light nav-btn"
            title="上一份"
          >
            <i class="fas fa-chevron-left"></i> 上一份
          </button>
          <span class="nav-info">
            {{ submissionIndex + 1 }} / {{ totalSubmissionsInList }}
          </span>
          <button
            @click="handleNavigate('next')"
            :disabled="submissionIndex >= totalSubmissionsInList - 1"
            class="btn btn-sm btn-light nav-btn"
            title="下一份"
          >
            下一份 <i class="fas fa-chevron-right"></i>
          </button>
        </div>
        <button @click="closeModal" class="close-button" title="关闭批改">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="grading-modal-body">
        <GradingSidebar
          :submission="editableSubmission"
          :currentTotalScore="currentTotalScore"
          :currentQuestionIndex="localCurrentQuestionIndex"
          @navigate-to-question="navigateToQuestion"
        />
        <div class="grading-main-panel">
          <QuestionGrading
            v-if="currentQuestion"
            :question="currentQuestion"
            :questionIndex="localCurrentQuestionIndex"
            @update:question="handleQuestionUpdate"
          />
           <div v-else class="no-question-display">
             <p>请选择一道题目进行批改，或检查答卷数据。</p>
           </div>
        </div>
      </div>

      <div class="modal-footer grading-modal-footer">
        <div class="footer-left-actions">
          <button v-if="['单选题', '多选题', '判断题'].includes('currentQuestion.questionTypeText')" @click="runAutoGradeObjective" class="btn btn-info" title="自动批改客观题并填充分数">
            <i class="fas fa-magic"></i> 自动批改客观题
          </button>
           <button v-else @click="autoGradeSubjective" class="btn btn-info" title="AI批改主观题">
            <i class="fas fa-magic"></i> AI批改主观题
          </button>

        </div>
        <div class="footer-right-actions">
          <button @click="handleSaveGrading" class="btn btn-success" title="保存当前批改进度">
            <i class="fas fa-save"></i> 保存批改
          </button>
          <button @click="handleSubmitGrading" class="btn btn-primary" title="提交批改并标记为已完成">
            <i class="fas fa-check-circle"></i> 提交并完成
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
// ... (script remains the same, but you might want to pass currentExam.name for the header)
import { ref, computed, watch } from 'vue';
import GradingSidebar from './GradingSidebar.vue';
import QuestionGrading from './QuestionGrading.vue';
import { deepClone } from '../utils';
import { GradeService } from '@/api/gradeApi';
const props = defineProps({
  show: Boolean,
  submissionData: Object, // The original submission object
  submissionIndex: Number,
  totalSubmissionsInList: Number,
  currentExamNameFromStore: String, // Added prop for exam name
});

const emit = defineEmits([
  'update:show',
  'save-submission',
  'submit-submission',
  'navigate-submission'
]);

const editableSubmission = ref(null);
const localCurrentQuestionIndex = ref(0);

watch(() => props.submissionData, (newData) => {
  if (newData) {
    editableSubmission.value = deepClone(newData);

console.log('Editable Submission:', editableSubmission.value);


    if (!editableSubmission.value.answers) { // Ensure answers array exists
        editableSubmission.value.answers = [];
    }
    localCurrentQuestionIndex.value = 0;
  } else {
    editableSubmission.value = null;
  }
}, { immediate: true, deep: true });


const currentQuestion = computed(() => {
  if (!editableSubmission.value || !editableSubmission.value.answers || editableSubmission.value.answers.length === 0 || localCurrentQuestionIndex.value < 0 || localCurrentQuestionIndex.value >= editableSubmission.value.answers.length) {
    return null;
  }
  return editableSubmission.value.answers[localCurrentQuestionIndex.value];
});

const currentTotalScore = computed(() => {
  if (!editableSubmission.value || !editableSubmission.value.answers) return 0;
  return editableSubmission.value.answers.reduce((total, answer) => {
    return total + (Number(answer.score) || 0);
  }, 0);
});

const navigateToQuestion = (index) => {
  localCurrentQuestionIndex.value = index;
};

const handleQuestionUpdate = (updatedQuestionData) => {
    if (editableSubmission.value && editableSubmission.value.answers) {
        // Find by questionId if available, otherwise by index. Prefer questionId for robustness.
        const qId = updatedQuestionData.id || (editableSubmission.value[localCurrentQuestionIndex.value] ? editableSubmission.value[localCurrentQuestionIndex.value].id : null);
        let questionIdx = -1;
        if(qId) {
            questionIdx = editableSubmission.value.answers.findIndex(q => q.questionId === qId);
        }
        if (questionIdx === -1 && localCurrentQuestionIndex.value < editableSubmission.value.answers.length) { // Fallback to current index if ID not found
            questionIdx = localCurrentQuestionIndex.value;
        }

        if (questionIdx !== -1) {
            // Merge: Retain existing properties, overwrite with updated ones
            editableSubmission.value.answers[questionIdx] = {
                ...editableSubmission.value.answers[questionIdx],
                ...updatedQuestionData
            };
        }
    }
};


const runAutoGradeObjective = () => {
  if (!editableSubmission.value || !editableSubmission.value.answers) return;
  editableSubmission.value.answers.forEach((answer, index) => {
    const originalAnswer = { ...answer }; // For comparison or specific updates
    if (['单选题', '多选题', '判断题'].includes(answer.type)) {
      let isCorrect = false;
      if (answer.type === '单选题') {
        isCorrect = answer.studentAnswer && answer.studentAnswer.length > 0 && answer.studentAnswer[0] === answer.standardAnswer;
      } else if (answer.type === '多选题') {
        const correctOptions = (answer.options || []).filter(opt => opt.isCorrect).map(opt => opt.label).sort();
        const studentSelectedOptions = (answer.studentAnswer || []).sort();
        isCorrect = JSON.stringify(correctOptions) === JSON.stringify(studentSelectedOptions) && correctOptions.length > 0; // Ensure not empty correct
      }
      answer.score = isCorrect ? answer.maxScore : 0;
      answer.comment = answer.score === answer.maxScore ? '自动批改：正确' : '自动批改：错误';

      // Ensure reactivity by updating the item in the array
      // Vue 3's reactivity should handle this, but if issues, replace item:
      // editableSubmission.value.answers.splice(index, 1, {...answer});
    }
  });
  // Force re-render of QuestionGrading if needed, though Vue 3 is good
  // localCurrentQuestionIndex.value = localCurrentQuestionIndex.value;
};

const  autoGradeSubjective= async () => {


  const data={
    question: currentQuestion.value.content,
    studentAnswer: currentQuestion.value.studentAnswer,
    reference: currentQuestion.value.standardAnswer,
    maxScore: currentQuestion.value.maxScore
  }


    console.log("currentQuestion", currentQuestion.value);

  const response = await GradeService.autoGrade(data)



  console.log("AI批改结果", response);
      if (response) {
        const score = response.score;
        const comment = response.comment || 'AI批改结果';
        // Update the current question with AI grading results
        editableSubmission.value.answers[localCurrentQuestionIndex.value].score = score;
        editableSubmission.value.answers[localCurrentQuestionIndex.value].comment = comment;
      }

  // Placeholder for AI grading logic
};




const closeModal = () => {
  emit('update:show', false);
};

const handleNavigate = (direction) => {
  // Save current changes before navigating, or prompt user
  // For now, just navigate
  emit('navigate-submission', direction);
};

const handleSaveGrading = () => {
  if (!editableSubmission.value) return;
  const submissionToSave = deepClone(editableSubmission.value);
  submissionToSave.score = currentTotalScore.value; // Update total score
  emit('save-submission', submissionToSave);
};

const handleSubmitGrading = () => {
  if (!editableSubmission.value) return;
  const submissionToSubmit = deepClone(editableSubmission.value);
  submissionToSubmit.score = currentTotalScore.value; // Update total score
  submissionToSubmit.status = 'graded';
  emit('submit-submission', submissionToSubmit);
};
</script>

<style scoped>
.grading-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1050; /* High z-index */
}

.grading-modal-content {
  background-color: #fff; /* var(--modal-background-color) */
  border-radius: 0.5rem; /* var(--border-radius) */
  box-shadow: 0 0.5rem 1.5rem rgba(0,0,0,0.2); /* var(--box-shadow-lg) */
  width: 95vw;
  height: 90vh;
  max-width: 1400px; /* Max width for large screens */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* Prevent content from spilling */
}

.grading-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1.5rem;
  border-bottom: 1px solid #dee2e6; /* var(--border-color) */
  background-color: #f8f9fa; /* var(--light-color) */
}

.grading-modal-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #343a40; /* var(--dark-color) */
  font-weight: 600;
}
.exam-name-header {
    font-size: 0.85rem;
    color: #6c757d; /* var(--text-muted-color) */
    font-weight: normal;
    margin-left: 0.5rem;
}

.grading-navigation {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.nav-btn {
  background-color: #fff;
  border: 1px solid #ced4da; /* var(--border-color) */
}
.nav-btn:hover { background-color: #e9ecef; }
.nav-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.nav-btn i { margin: 0 0.2rem; }

.nav-info {
  font-size: 0.9rem;
  color: #495057;
  padding: 0 0.5rem;
  background-color: #e9ecef;
  border-radius: 0.2rem;
  padding: 0.25rem 0.5rem;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.6rem;
  cursor: pointer;
  color: #6c757d; /* var(--text-muted-color) */
  padding: 0.25rem 0.5rem;
}
.close-button:hover {
  color: #dc3545; /* var(--danger-color) */
}


.grading-modal-body {
  display: flex;
  flex-grow: 1; /* Take up remaining vertical space */
  overflow: hidden; /* Prevent body from causing main scroll */
  height: calc(100% - 110px); /* Adjust based on header/footer height */
}

.grading-main-panel {
  flex-grow: 1;
  overflow-y: auto; /* Allow scrolling for question content */
  height: 100%; /* Required for overflow to work correctly */
  position: relative; /* For potential absolute positioned children */
}
.no-question-display {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    text-align: center;
    color: #6c757d; /* var(--text-muted-color) */
    font-size: 1.1rem;
    padding: 2rem;
}

.grading-modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1.5rem;
  border-top: 1px solid #dee2e6; /* var(--border-color) */
  background-color: #f8f9fa; /* var(--light-color) */
}
.footer-left-actions, .footer-right-actions {
  display: flex;
  gap: 0.75rem;
}

/* Basic button styling (can be global) */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  font-weight: 500;
  border-radius: 0.25rem; /* var(--border-radius) */
  cursor: pointer;
  text-decoration: none;
  border: 1px solid transparent;
  transition: all 0.2s ease-in-out;
}
.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 0.8rem;
}
.btn i { margin-right: 0.4rem; }

.btn-primary { background-color: #007bff; color: white; border-color: #007bff; }
.btn-primary:hover { background-color: #0056b3; border-color: #0056b3; }
.btn-success { background-color: #28a745; color: white; border-color: #28a745; }
.btn-success:hover { background-color: #1e7e34; border-color: #1e7e34; }
.btn-info { background-color: #17a2b8; color: white; border-color: #17a2b8; }
.btn-info:hover { background-color: #117a8b; border-color: #117a8b; }
.btn-light { background-color: #f8f9fa; color: #212529; border-color: #ced4da;}
.btn-light:hover { background-color: #e2e6ea; border-color: #b3b9c0;}

</style>
